import 'dart:collection';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:native_dio_adapter/native_dio_adapter.dart';

import '../AppConfig/CityLIstData.dart';
import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../http/api.dart';

class UpEmptyLine extends StatefulWidget {

  const UpEmptyLine({super.key, required this.emptyData, required this.type});
  final Map emptyData;
  //1.修改
  final int type;

  @override
  State<UpEmptyLine> createState() => _UpEmptyLineState();
}

class _UpEmptyLineState extends State<UpEmptyLine> {
  late String startCity="+ 选择";
  late String endCity="+ 选择";

   int isCheck=1;

  DateTime _showDate = DateTime.now();
  var _selectedTime;
  late String startTime="";
  late String endTime="";
  int startType=-1;
  int endType=-1;
  List startNameList=[];
  List endNameList=[];
  int chooseStartTime=-1;
  int chooseEndTime=-1;
  List startCodeList=[];
  List endCodeList=[];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.type==1) {
      if(widget.emptyData['loadPlace']['county']!=null&&widget.emptyData['loadPlace']['county']!="") startCity=widget.emptyData['loadPlace']['county'];
      if((widget.emptyData['loadPlace']['county']==""||widget.emptyData['loadPlace']['county']==null)&&(widget.emptyData['loadPlace']['city']!=""||widget.emptyData['loadPlace']['city']!=null)) startCity=widget.emptyData['loadPlace']['city'];
      if(widget.emptyData['loadPlace']['city']==""||widget.emptyData['loadPlace']['city']==null) startCity=widget.emptyData['loadPlace']['province'];
      if(widget.emptyData['unloadPlace']['county']!=""&&widget.emptyData['unloadPlace']['county']!=null) endCity=widget.emptyData['unloadPlace']['county'];
      if((widget.emptyData['unloadPlace']['county']==""||widget.emptyData['unloadPlace']['county']==null)&&(widget.emptyData['unloadPlace']['city']!=""||widget.emptyData['unloadPlace']['city']!=null)) endCity=widget.emptyData['unloadPlace']['city'];
      if(widget.emptyData['unloadPlace']['city']==""||widget.emptyData['unloadPlace']['city']==null) endCity=widget.emptyData['unloadPlace']['province'];
      startTime=widget.emptyData['loadTime'];
      endTime=widget.emptyData['unloadTime'];
      startNameList=[widget.emptyData['loadPlace']['county'],widget.emptyData['loadPlace']['city'],widget.emptyData['loadPlace']['county']];
      endNameList=[widget.emptyData['unloadPlace']['county'],widget.emptyData['unloadPlace']['city'],widget.emptyData['unloadPlace']['county']];
    }
  }

void upLoadEmpty()async{

  ApiManager.postData(
    context,
    "api/goods/idle/vehicle/add",
    {
      "loadPlace": {
        "province": startNameList[0],
        "city": startNameList[1],
        "county": startNameList[2],
        "areaCode": startCodeList.last,
      },
      "unloadPlace": {
        "province": endNameList[0],
        "city": endNameList[1],
        "county": endNameList[2],
        "areaCode":endCodeList.last,
      },
      "loadTime": startTime+":00",
      "unloadTime": endTime+":00"
    },
        (responseData) {
      BrnToast.show("添加成功", context);
      Navigator.pop(context, "success");
    },
  );
}
  void editEmpty()async{
    ApiManager.postData(
      context,
      "api/goods/idle/vehicle/edit",
      {
        "id":widget.emptyData['id'],
        "loadPlace": {
          "province": startNameList[0],
          "city": startNameList[1],
          "county": startNameList[2],
          "areaCode": startCodeList.last,
        },
        "unloadPlace": {
          "province": endNameList[0],
          "city": endNameList[1],
          "county": endNameList[2],
          "areaCode":endCodeList.last,
        },
        "loadTime": startTime+":00",
        "unloadTime": endTime+":00"
      },
          (responseData) {
        BrnToast.show("修改成功", context);
        Navigator.pop(context, "success");
      },
    );
  }
  //删除空车
  void deleEmptyAction(String drvId)async{
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(MyServiceUrl.header + 'api/goods/idle/vehicle/delete',
      data: [
        {"id":widget.emptyData['id']}
      ],
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("删除成功", context, duration: BrnDuration.short,);
          Navigator.pop(context,"success");
        } else {

          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });


  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "上报空车",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [

          Badge(
            label:Text("1"),
            child:GestureDetector(
              child: Row(
                children: [

                  Image.asset("lib/Images/RoadLine/消息icon.png",width: 16.w,height: 16.h,),
                  SizedBox(width: 10.w,),
                ],
              ),
              onTap: (){

              },
            ),


          ),
        ],
      ),

      body:Column(
        children: [
          Expanded(child:  ListView(

            children: [
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                padding: EdgeInsets.only(top: 8.h,bottom: 8.h),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Row(
                  children: [
                    SizedBox(width: 8.w,),
                    Text("上报空车，更快找货",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                    SizedBox(width: 4.w,),
                    Text("仅可上传一条空车信息",style: TextStyle(color:Color.fromRGBO(231, 112, 27, 0.85),fontWeight: FontWeight.w600,fontSize: 12.sp),),
                  ],
                ),
              ),
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                padding: EdgeInsets.only(top: 8.h,bottom: 8.h),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,

                  children: [
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Image.asset("lib/Images/RoadLine/绿色圆圈.png",height: 9.h,width: 9.w,),
                        SizedBox(width: 4.w,),
                        Text("请选择装货地",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),

                    GestureDetector(
                      child:  Container(
                        margin: EdgeInsets.only(left: 18.w),
                        padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 5.h,bottom: 5.h),
                        constraints: BoxConstraints(
                          minWidth: 65.w,
                          maxWidth:200.w, // 限制文本最大宽度
                        ),
                        height: 25.h,
                        decoration: BoxDecoration(
                            color:startCity!="+ 选择"?Color.fromRGBO(251, 236, 228, 1) :Color.fromRGBO(240, 240, 240, 1),
                            borderRadius: BorderRadius.all(Radius.circular(5))),
                        // child:Center(
                        child:   Text(startCity,style: TextStyle(color: startCity!="+ 选择"?MyColors.themeColor: Colors.black,fontSize: 13.sp,fontWeight: FontWeight.w400),),
                        // ),

                      ),
                      onTap: ()async{

                        final result = await showModalBottomSheet(
                            context: context,
                            isScrollControlled: true,

                            builder: (BuildContext context) {
                              return ChooseAddressSheet(addressType: 1,
                              );
                            }
                        );
                        if (result != null) {
                          setState(() {
                            startCity=result[0];
                            startType=result[1];
                            startNameList=[result[2],result[3],result[4]];
                            print(startNameList);
                            for (String cityName in startNameList) {
                              String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                              if (cityCode != "") {
                                print('$cityName 的城市编码为：$cityCode');
                                // cityCode=getCodeResult(cityCode);
                                startCodeList.add(cityCode);

                              } else {
                                print('未找到城市 $cityName');
                              }
                            }
                          });
                        }
                      },
                    ),
                    SizedBox(height: 8.h,),
                    Divider(height: 1.h,color: Color.fromRGBO(248, 248, 248, 1),),
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Image.asset("lib/Images/RoadLine/红色圆圈.png",height: 9.h,width: 9.w,),
                        SizedBox(width: 4.w,),
                        Text("请选择卸货地",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    GestureDetector(
                      child:  Container(
                        margin: EdgeInsets.only(left: 18.w),
                        padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 5.h,bottom: 5.h),
                        constraints: BoxConstraints(
                          minWidth: 65.w,
                          maxWidth:200.w, // 限制文本最大宽度
                        ),
                        height: 25.h,
                        decoration: BoxDecoration(
                            color:endCity!="+ 选择"?Color.fromRGBO(251, 236, 228, 1) :Color.fromRGBO(240, 240, 240, 1),
                            borderRadius: BorderRadius.all(Radius.circular(5))),
                        // child:Center(
                        child:   Text(endCity,style: TextStyle(color: endCity!="+ 选择"?MyColors.themeColor: Colors.black,fontSize: 13.sp,fontWeight: FontWeight.w400),),
                        // ),
                      ),
                      onTap: ()async{

                        final result = await showModalBottomSheet(
                            context: context,
                            isScrollControlled: true,
                            builder: (BuildContext context) {
                              return ChooseAddressSheet(addressType: 2,
                              );
                            }
                        );
                        if (result != null) {
                          setState(() {
                            endCity=result[0];
                            endType=result[1];
                            endNameList=[result[2],result[3],result[4]];
                            print(endNameList);
                            for (String cityName in endNameList) {
                              String cityCode = getCityCodeByName(MyCityListData.CityList, cityName);
                              if (cityCode != "") {
                                print('$cityName 的城市编码为：$cityCode');
                                cityCode=getCodeResult(cityCode);
                                endCodeList.add(cityCode);

                              } else {
                                print('未找到城市 $cityName');
                              }
                            }
                          });
                        }
                      },
                    ),
                    SizedBox(height: 8.h,),
                    Divider(height: 1.h,color: Color.fromRGBO(248, 248, 248, 1),),
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Image.asset("lib/Images/RoadLine/黑色圆圈.png",height: 9.h,width: 9.w,),
                        SizedBox(width: 4.w,),
                        Text("请选择时间段",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        Text("(若空车时间已过期，则不再展示于平台)",style: TextStyle(color: MyColors.authTipColor,fontSize: 11.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Container(
                      height: 30.h,
                      margin: EdgeInsets.only(right: 18.w,left: 18.w),
                      decoration: BoxDecoration(
                          color: Color.fromRGBO(240, 240, 240, 1),
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(),
                          Image.asset("lib/Images/RoadLine/时间icon.png",height: 15.h,width: 15.w,color: MyColors.authTipColor,),
                          GestureDetector(
                            child: Text(startTime==""?"开始时间":startTime.substring(0, 16),style: TextStyle(color: Colors.black,fontSize: 12.sp)),
                            onTap: ()async{
                              final result= await showModalBottomSheet(
                                context: context,
                                builder: (BuildContext context) {
                                  return dataTimeSheet(type: 1, startTime: startTime, endTime: endTime,
                                  );
                                },
                              );
                              if (result != null) {

                                setState(() {
                               startTime=result[0];
                               endTime=result[1];
                                });
                              }
                            },
                          ),
                          Text("至",style: TextStyle(color: Colors.black,fontSize: 12.sp)),
                          GestureDetector(
                            child: Text(endTime==""?"结束时间":endTime.substring(0, 16),style: TextStyle(color: Colors.black,fontSize: 12.sp)),
                            onTap: ()async{
                              final result= await showModalBottomSheet(
                                context: context,
                                builder: (BuildContext context) {
                                  return dataTimeSheet(type: 2, startTime: startTime, endTime: endTime,
                                  );
                                },
                              );
                              if (result != null) {
                                setState(() {
                                  startTime=result[0];
                                  endTime=result[1];
                                });
                              }
                            },

                          ),
                          SizedBox(),
                        ],
                      ),

                    ),



                  ],

                ),
              ),

            ],
          ),),
          Container(
            height: 85.h ,
            padding: EdgeInsets.only(left: 15.w,right: 15.w,bottom: 40.h,top: 10.h),
            color: Colors.white,

            width: double.infinity,

            child: Row(
              children: [
                if(widget.emptyData.isNotEmpty)
                BrnSmallOutlineButton(
                  title: '删除',
                  textColor: MyColors.themeColor,
                  lineColor:MyColors.themeColor,
                  width: (screenSize.width-40.w)/2,
                  fontSize: 16.sp,
                   radius: 30,
                  onTap: () {
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return BrnDialog(
                          titleText: "确定删除空车信息吗？",
                          actionsWidget: [
                            TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            ),
                            TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                                deleEmptyAction("");
                              },
                              child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                            ),

                          ],
                        );
                      },
                    );
                  },
                ),
                if(widget.emptyData.isNotEmpty)
                SizedBox(width: 10.w,),
                BrnSmallMainButton(
                  title: widget.type==1?"修改":"添加",
                  bgColor: MyColors.themeColor,
                  fontSize: 16.sp,
                  width:widget.emptyData.isEmpty?(screenSize.width-30.w): (screenSize.width-40.w)/2,
                  radius: 30,
                  onTap: () {
                    if(startType==-1&&widget.type==1){
                      startNameList[0]=widget.emptyData['loadPlace']['province'];
                      startNameList[1]=widget.emptyData['loadPlace']['city'];
                      startNameList[2]=widget.emptyData['loadPlace']['county'];
                      startCodeList.add(widget.emptyData['loadPlace']['areaCode']);
                    }
                    if(endType==-1&&widget.type==1){
                      endNameList[0]=widget.emptyData['unloadPlace']['province'];
                      endNameList[1]=widget.emptyData['unloadPlace']['city'];
                      endNameList[2]=widget.emptyData['unloadPlace']['county'];
                      endCodeList.add(widget.emptyData['unloadPlace']['areaCode']);
                    }

                    if(startNameList.isEmpty){
                      BrnToast.show("请选择装货城市", context);
                    }else if(endNameList.isEmpty){
                      BrnToast.show("请选择卸货城市", context);
                    }else if(startNameList[1]==""){
                      BrnToast.show("装货地请至少选择至市", context);
                    }else if(endNameList[1]==""){
                      BrnToast.show("卸货地请至少选择至市", context);
                    }else {
                      if(widget.type==1){
                        editEmpty();
                      }else{
                        upLoadEmpty();
                      }

                    }
                  },
                ),

              ],
            ),

          ),

        ],
      ),


    );

  }

}
class ChooseAddressSheet extends StatefulWidget {
  const ChooseAddressSheet({super.key, required this.addressType});
    final int addressType;
  @override
  State<ChooseAddressSheet> createState() => _ChooseAddressSheetState();
}

class _ChooseAddressSheetState extends State<ChooseAddressSheet> {
  String chooseName="";
  List<String> historyLis=['苏州','无锡','黑龙江'];
  List isChooseList=[];
  String selectedProvince = "";
  String selectedCity = "";
  String selectedDistrict = "";
  String currentLevel = "province"; // 初始显示省份
  int chooseType =-1;
  List<bool> isSelected = List.generate(3, (index) => false);
 @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // getHisCity();
  }
  void getHisCity()async{
    historyLis  =  (await HisCityManager.getHisCitysList());
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 550.h,
      padding: EdgeInsets.only(top: 12.h,left: 16.w,right: 16.w,bottom: 44.h),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      child: Column(
        children: [
          Expanded(child:  Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(widget.addressType==1? "lib/Images/RoadLine/绿色圆圈.png":"lib/Images/RoadLine/红色圆圈.png",height: 9.h,width: 9.w,),
                  SizedBox(width: 4.w,),
                  Text(widget.addressType==1? "请选择装货地" :"请选择卸货地",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                ],
              ),
              SizedBox(height: 10.h,),
              Text("已选地区（仅可选择一个地区）",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
              SizedBox(height: 8.h,),
              if(chooseName!="")
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.only(left: 2.w,right: 2.w),
                      constraints: BoxConstraints(
                        minWidth: 70.w,
                        maxWidth:200.w, // 限制文本最大宽度
                      ),
                      height:25.h,
                      decoration: BoxDecoration(
                          color: Color.fromRGBO(251, 236, 228, 1),
                          borderRadius: BorderRadius.all(Radius.circular(5))),

                      child:  GestureDetector(
                        child: Center(
                          widthFactor:1 ,
                          child: Text(chooseName+" x",overflow: TextOverflow.ellipsis,style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                        ),
                        onTap: (){
                          setState(() {
                            chooseName="";
                          });
                        },
                      ),
                    ),
                    SizedBox(height: 8.h,),
                  ],
                ),

              // Text("历史地区",style: TextStyle(color: Colors.black,fontSize: 13.sp),),
              // SizedBox(height: 8.h,),
              // if(historyLis.length>0)
              //   Row(
              //
              //     children: List.generate(
              //       isSelected.length,
              //           (index) => GestureDetector(
              //         onTap: () {
              //           setState(() {
              //             // 单选逻辑
              //             isSelected = List.generate(isSelected.length, (i) => i == index);
              //             chooseName=historyLis[index];
              //           });
              //         },
              //         child: Container(
              //             margin: EdgeInsets.only(right: 10.w),
              //             width: 70.w,
              //             padding: EdgeInsets.only(top: 2.h,bottom: 2.h,left: 6.w,right: 6.w),
              //             color: isSelected[index] ?Color.fromRGBO(251, 236, 228, 1):MyColors.backgreyColor,
              //             child: Center(
              //               child: Text(historyLis[index],style: TextStyle(color:isSelected[index] ?MyColors.themeColor:Colors.black ),),
              //             )
              //         ),
              //       ),
              //     ),
              //   ),
            SizedBox(height: 8.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("请选择装货地",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                  if (currentLevel!="province")

                    GestureDetector(
                      child: Text("返回上一级",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                      onTap: (){
                        setState(() {
                          if(currentLevel == "city")
                            currentLevel = "province";
                          if(currentLevel == "district")
                            currentLevel = "city";
                        });
                      },
                    ),
                ],
              ),
              Container(
                height: 330.h,
                child:   Column (

                  children: [
                    if (currentLevel == "province")
                      buildButtonRow("省", getItems(getProvinces()), (value) {
                        setState(() {
                          selectedProvince = value;
                          selectedCity = "";
                          selectedDistrict = "";
                          currentLevel = "city";
                          updateSelectedAreas();
                        });
                      }),

// 在 _MyHomePageState 类的 build 方法中，如果当前级别为 "city"，则显示市的按钮行
                    if (currentLevel == "city")
                      buildButtonRow("市", getItems(getCities(selectedProvince)), (value) {
                        setState(() {
                          selectedCity = value;
                          selectedDistrict = "";
                          currentLevel = "district";
                          updateSelectedAreas();
                        });
                      }),
                    if (currentLevel == "district"&&selectedCity =="全省")
                      buildButtonRow("市", getItems(getCities(selectedProvince)), (value) {
                        setState(() {
                          selectedCity = value;
                          selectedDistrict = "";
                          currentLevel = "district";
                          updateSelectedAreas();
                        });
                      }),
// 在 _MyHomePageState 类的 build 方法中，如果当前级别为 "district"，则显示区的按钮行
                    if (currentLevel == "district"&&selectedCity !="全省")
                      buildButtonRow("区", getItems(getDistricts(selectedProvince, selectedCity)), (value) {
                        setState(() {
                          selectedDistrict = value;
                          updateSelectedAreas();
                        });
                      }),
                  ],
                ),
              ),


            ],
          ),
          ),
          Container(
            height: 35.h,
            color: Colors.white,
            child:    Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                BrnSmallOutlineButton(
                  title: '重置',
                  textColor: MyColors.themeColor,
                  lineColor: MyColors.themeColor,
                  radius: 30,
                  width: 150.w,
                  fontSize: 14.sp,
                  onTap: () {
                    setState(() {
                      chooseName="";
                      chooseType=-1;
                      isSelected=[false,false,false];
                      currentLevel = "province";
                    });

                  },
                ),

                BrnSmallMainButton(
                  title: '确定',
                  bgColor: MyColors.themeColor,
                  textColor: Colors.white,
                  width: 150.w,
                  radius: 30,
                  fontSize: 14.sp,
                  onTap: () {
                    if(chooseName!="") {
                      Navigator.pop(context, [chooseName,chooseType,selectedProvince,selectedCity,selectedDistrict]);
                    }else{
                      BrnToast.show('请选择地址', context);
                    }
                  },
                ),
              ],
            ),
          )
        ],
      ),

    );
  }
  void updateSelectedAreas() {


      if (selectedDistrict.isNotEmpty) {
       chooseType=2;
        chooseName=selectedDistrict;
      } else if (selectedCity.isNotEmpty && selectedDistrict.isEmpty) {
        chooseType=1;
        chooseName=selectedCity;
      } else if (selectedProvince.isNotEmpty && selectedDistrict.isEmpty &&
          selectedCity.isEmpty) {
        chooseType=0;
        chooseName=selectedProvince;
      }

  }
  List<String> getProvinces() {
    return MyCityListData.CityList.map((province) => getProvinceName(province)).toList();
  }

  List<String> getCities(String province) {
    for (var item in MyCityListData.CityList) {
      if (getProvinceName(item) == province) {
        List<Map<String, dynamic>> cities = item["children"];
        return ['全省', ...cities.map((city) => getCityName(city)).toList()];
      }
    }
    return [];
  }

  List<String> getDistricts(String province, String city) {
    if (city == '全省') {
      List<String> districts = [];
      for (var item in MyCityListData.CityList) {
        if (getProvinceName(item) == province) {
          for (var child in item["children"]) {
            districts.addAll(child["children"].map<String>((district) => getCityName(district)).toList());
          }
        }
      }
      return districts;
    }

    for (var item in MyCityListData.CityList) {
      if (getProvinceName(item) == province) {
        for (var child in item["children"]) {
          if (getCityName(child) == city) {
            return ['全市', ...child["children"].map<String>((district) => getCityName(district)).toList()];
          }
        }
      }
    }
    return [];
  }

  List<String> getItems(List<String> items) {
    items.remove('全省');
    items.remove('全市');
    if (items.isEmpty) {
      return items;
    }
    return items;
  }

  String getProvinceName(Map<String, dynamic> province) {
    return province["cityShortName"] ?? '未知';
  }

  String getCityName(Map<String, dynamic> city) {
    return city["cityName"] ?? '未知';
  }
  Widget buildButtonRow(String label, List<String> items, Function(String) onPressed) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [

        Text(label, style: TextStyle(fontSize: 18)),
        SizedBox(height: 8),
        Wrap(
          spacing:8.w,
          runSpacing: 4.h,
          children: items.map((item) => Container(
            width: 74.w,
            child: InkWell(
              onTap: () => onPressed(item),
              child: Container(
                padding: EdgeInsets.all(8.0),
                decoration: BoxDecoration(
                  color: item == getSelectedItem() ||item =="全省"? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor,
                  borderRadius: BorderRadius.circular(5.0),
                ),
                child: Center(
                  child: Text(
                    item,
                    style: TextStyle(
                      overflow: TextOverflow.ellipsis,
                      fontSize: 13.sp,
                      color: item == getSelectedItem() ? MyColors.themeColor : Colors.black,
                    ),
                  ),
                ),
              ),
            ),
          )).toList(),
        ),
      ],
    );
  }

  String getSelectedItem() {
    switch (currentLevel) {
      case "province":
        return selectedProvince;
      case "city":
        return selectedCity;
      case "district":
        return selectedDistrict;
      default:
        return '';
    }
  }
}


class dataTimeSheet extends StatefulWidget {
  const dataTimeSheet({super.key, required this.type, required this.startTime, required this.endTime});
  final int type;
  final String startTime;
  final String endTime;
  @override
  State<dataTimeSheet> createState() => _dataTimeSheetState();
}

class _dataTimeSheetState extends State<dataTimeSheet> {
  DateTime selectedDate = DateTime.now();
  int selectedYear = DateTime.now().year;
  int selectedMonth = DateTime.now().month;
  int selectedDay = DateTime.now().day;
  int selectedHour = DateTime.now().hour;
  late List<int> years;
  late FixedExtentScrollController yearController;
  late FixedExtentScrollController monthController;
  late FixedExtentScrollController dayController;
  late FixedExtentScrollController hourController;
  String startTime ="";
  String endTime ="";
  int timeType=1;
  @override
  void initState() {
    super.initState();
    startTime=widget.startTime;
    endTime=widget.endTime;
    DateTime selectedDate = DateTime.now();
    int selectedYear = DateTime.now().year;
    int selectedMonth = DateTime.now().month;
    int selectedDay = DateTime.now().day;
    int selectedHour = DateTime.now().hour;
    int currentYear = DateTime.now().year;
    years = List.generate(6, (index) => currentYear + index);
    // 设置初始滚动位置
    yearController = FixedExtentScrollController(initialItem: years.indexOf(selectedYear));
    monthController = FixedExtentScrollController(initialItem: selectedMonth - 1);
    dayController = FixedExtentScrollController(initialItem: selectedDay - 1);
    hourController = FixedExtentScrollController(initialItem: selectedHour);
    startTime=DateTime.now().toString().substring(0, 13)+":00";
  }
  @override
  int getDaysInMonth(int year, int month) {
    return DateTime(year, month + 1, 0).day;
  }

  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.w,bottom: 40.h),
      height: 330.h,
        decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(10)),
          color: Colors.white,
    ),
      child:Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(onPressed: (){
                Navigator.pop(context);
              }, child: Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.access_time,color: MyColors.textColor,),
                  Text("选择时间",style:TextStyle(color: Colors.black,fontSize: 16.sp),),
                ],
              ),

              TextButton(onPressed: (){
                if(startTime==""){
                  BrnToast.show("请选择开始时间", context);
                }else if(endTime==""){
                  BrnToast.show("请选择结束时间", context);
                }else{
                  print([startTime,endTime]);
                  Navigator.pop(context,[startTime,endTime]);
                }

              }, child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp))),
            ],
          ),
          Divider(height: 16.h,color: MyColors.backgreyColor,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(width: 10.w,),
              GestureDetector(
                child:  Column(
                  children: [
                    Text(startTime==""?"开始时间":startTime,style: TextStyle(color:timeType==1?MyColors.themeColor: Colors.black,fontSize: 13.sp),),
                    Container(
                      height: 2.h,width:20.w,
                      color:timeType==1? MyColors.themeColor:Colors.white,
                    )
                  ],
                ),
                onTap: (){
                  setState(() {
                    timeType=1;
                  });
                },
              ),

              Text("至",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
              GestureDetector(
                child: Column(
                  children: [
                    Text(endTime==""?"结束时间":endTime,style: TextStyle(color: timeType==2?MyColors.themeColor: Colors.black,fontSize: 13.sp),),
                    Container(
                      height: 2.h,width:20.w,
                      color:timeType==2? MyColors.themeColor:Colors.white,
                    )
                  ],
                ),
                onTap: (){
                  setState(() {
                    timeType=2;
                  });
                },
              ),

              SizedBox(width: 10.w,),
            ],
          ),
          Divider(height: 16.h,color: MyColors.backgreyColor,),

          Text("时间格式:年-月-日 时",style: TextStyle(color: Colors.black),),
          SizedBox(height: 4.h,),
          Container(
            decoration: BoxDecoration(
              border: Border.all(
                color: Color.fromRGBO(224, 227, 234, 1),
                width: 1,
              ),
              borderRadius: BorderRadius.circular(5.0), // 可选，添加圆角
            ),
            child:  Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildPicker(
                  items: generateYearList(),
                  controller: yearController,
                  onChanged: (value) {
                    setState(() {
                      selectedYear = value;
                      timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00"
                          :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00";
                    });
                  },
                ),
                _buildPicker(
                  items: List.generate(12, (index) => index + 1),
                  controller: monthController,
                  onChanged: (value) {
                    setState(() {
                      selectedMonth = value;
                      timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00"
                          :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00";
                    });
                  },
                ),
                _buildPicker(
                  items: List.generate(getDaysInMonth(selectedYear, selectedMonth), (index) => index + 1),
                  controller: dayController,
                  onChanged: (value) {
                    setState(() {
                      selectedDay = value;
                      timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00"
                          :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00";
                    });
                  },
                ),
                _buildPicker(
                  items: List.generate(24, (index) => index),
                  controller: hourController,
                  onChanged: (value) {
                    setState(() {
                      selectedHour = value;
                      timeType==1?startTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00"
                          :endTime=selectedYear.toString()+"-"+selectedMonth.toString().padLeft(2, '0')+"-"+selectedDay.toString().padLeft(2, '0')+" "+selectedHour.toString().padLeft(2, '0')+":00";
                    });
                  },
                ),
              ],
            ),
          ),


        ],
      )



    );
  }
  Widget _buildPicker({
    required List<int> items,
    required FixedExtentScrollController controller,
    required ValueChanged<int> onChanged,
  }) {
    return Container(
      height: 150.0,
      width: 80.0,
      child: CupertinoPicker(
        itemExtent: 40.0,
        onSelectedItemChanged: (index) {
          onChanged(items[index]);
        },
        selectionOverlay: _buildSelectionOverlay(),
        children: items.map((item) => _buildPickerItem(item)).toList(),
        // 使用初始化的控制器
        scrollController: controller,
      ),
    );
  }

  Widget _buildPickerItem(int item) {
    // 将月份和日期格式化为两位数
    String formattedItem = item.toString().padLeft(2, '0');

    return Container(
      alignment: Alignment.center,
      child: Text(formattedItem),
    );
  }

  Widget _buildSelectionOverlay() {
    return Container(
      height: 40.0,
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
          bottom: BorderSide(color: Color.fromRGBO(220, 224, 231, 1), width: 1.0.h),
        ),
      ),
    );
  }

  // 生成年份列表，包括当前年份和之后的5年
  List<int> generateYearList() {
    int currentYear = DateTime.now().year;
    List<int> years = List.generate(6, (index) => currentYear + index);
    return years;
  }
}
